<template>
    <view class="page bg-fff">
        <view class="header flex top-20">
            <button class="weekBtn clearBtn flex font12" @click="clickPreviousWeek">
                <up-icon name="arrow-left" size="12" color="#8A8A8A"></up-icon>
                <tetx class="left-5">上一周</tetx>
            </button>

            <text class="fontBold font14">{{ currentWeek.start }} - {{ currentWeek.end }}</text>

            <button class="weekBtn clearBtn flex font12" :class="{ 'col-grey': isNextWeekDisabled }"
                @click="handleNextWeek">
                <text class="right-5">下一周</text>
                <up-icon name="arrow-right" size="12" :color="isNextWeekDisabled ? '#8A8A8A' : '#333333'"></up-icon>
            </button>
        </view>

        <view class="formWrap">
            <up-form labelPosition="left" :model="form" labelWidth="80" :rules="rules" ref="statisticsFormRef">
                <up-form-item label="项目名称" borderBottom v-if="productTitle">
                    <view>{{ productTitle }}</view>
                </up-form-item>

                <up-form-item label="真实来电" prop="buy" borderBottom>
                    <up-input v-model="form.buy" placeholder="请输入真实来电总数" border="none" :disabled="formDisabled"></up-input>
                </up-form-item>

                <up-form-item label="真实到访" prop="view" borderBottom>
                    <up-input v-model="form.view" :focus="formFocus" placeholder="请输入真实到访" border="none" :disabled="formDisabled"></up-input>
                </up-form-item>

                <up-form-item label="真实签约" prop="sign" borderBottom>
                    <up-input v-model="form.sign" placeholder="请输入真实签约" border="none" :disabled="formDisabled"></up-input>
                </up-form-item>
            </up-form>

            <view class="btn bg-primary font18 col-fff text-center top-20" @click="clickModify" v-if="formDisabled">
                修改
            </view>

            <view class="btn bg-theme font18 col-fff text-center top-20" @click="clickSubmit" v-else>
                提交
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useIndexStore, useUserInfoStore } from '@/store/index';
import { onLoad } from '@dcloudio/uni-app';
import { submitCreateStatisticsAPI, getWeekVisitDataAPI, submitModifyStatisticsAPI } from '@/common/api/my';

const indexStore = useIndexStore();
const userInfoStore = useUserInfoStore();

let currentDate = ref(new Date());
let currentWeek = ref({});

// 添加计算属性判断是否禁用下一周按钮
const isNextWeekDisabled = computed(() => {
    const today = new Date();
    const nextWeekStart = new Date(currentDate.value);
    nextWeekStart.setDate(nextWeekStart.getDate() + 7);

    // 将时间设置为当天的开始（00:00:00）
    today.setHours(0, 0, 0, 0);
    nextWeekStart.setHours(0, 0, 0, 0);

    // 如果下一周的开始日期大于今天，则禁用按钮
    return nextWeekStart > today;
});

let productTitle = ref('');
let form = ref({
    id: '',
    product: '',
    product_title: '',
    view: '',
    buy: '',
    sign: '',
    start_date: '',
    end_date: ''
})

let rules = ref({
    view: [{
        required: true,
        transform: (value) => {
            return String(value);
        },
        message: '请输入真实到访',
        trigger: ['change'],
    }],
    buy: [{
        required: true,
        transform: (value) => {
            return String(value);
        },
        message: '请输入真实来电总数',
        trigger: ['change'],
    }],
    sign: [{
        required: true,
        transform: (value) => {
            return String(value);
        },
        message: '请输入真实签约',
        trigger: ['change'],
    }]
})

// 表单引用  
const statisticsFormRef = ref(null);

// 缓存某一周的到访数据
let catchWeekData = ref({});

// 表单是否禁用
let formDisabled = ref(false)

// 表单是否聚焦
let formFocus = ref(false);

// 页面加载
onLoad((options) => {
    // 初始化currentDate
    currentDate.value = new Date();
    
    let startDate = options.startDate && options.startDate !== 'undefined' ? options.startDate : '';
    let endDate = options.endDate && options.endDate !== 'undefined' ? options.endDate : '';
    
    if(startDate && endDate) {
        form.value.start_date = startDate;
        form.value.end_date = endDate;
        // 根据传入的startDate更新currentDate
        const [year, month, day] = startDate.split('-');
        // 确保创建有效的Date对象
        const newDate = new Date(year, parseInt(month) - 1, parseInt(day));
        if (!isNaN(newDate.getTime())) {
            currentDate.value = newDate;
        }
    }
    
    initPage();
})

// 初始化页面
async function initPage() {
    updateWeek()
}

// 更新本周日期
async function updateWeek() {
    currentWeek.value = getWeekRange(currentDate.value)
    // 获取缓存数据
    const key = `${currentWeek.value.start.replace(/\./g, '-')}${currentWeek.value.end.replace(/\./g, '-')}`;
    if (catchWeekData.value[key]) {
        form.value = {...catchWeekData.value[key]};
    } else {
        await getVisitData();
    }

    //如果有数据disabled为true
    formDisabled.value = form.value.id ? true : false;
}

// 获取本周日期
function getWeekRange(date) {
    // 确保传入的是有效的Date对象
    if (!(date instanceof Date) || isNaN(date.getTime())) {
        date = new Date();
    }
    
    let current = new Date(date);
    let firstDay = current.getDate() - current.getDay() + 1;
    let lastDay = firstDay + 6;
    
    // 创建新的Date对象，避免修改原始日期
    let startDate = new Date(current);
    startDate.setDate(firstDay);
    
    let endDate = new Date(current);
    endDate.setDate(lastDay);
    
    return {
        start: formatDate(startDate),
        end: formatDate(endDate)
    };
}

// 格式化日期
function formatDate(date) {
    let year = date.getFullYear();
    let month = (date.getMonth() + 1).toString().padStart(2, '0');
    let day = date.getDate().toString().padStart(2, '0');
    return `${year}.${month}.${day}`;
}

// 上一周
async function clickPreviousWeek() {
    let newDate = new Date(currentDate.value);
    newDate.setDate(newDate.getDate() - 7);
    currentDate.value = newDate;
    updateWeek();
}

// 下一周
function handleNextWeek() {
    if (!isNextWeekDisabled.value) {
        clickNextWeek();
    }
}

function clickNextWeek() {
    let newDate = new Date(currentDate.value);
    newDate.setDate(newDate.getDate() + 7);
    currentDate.value = newDate;
    updateWeek();
}

//获取到访数据
async function getVisitData() {
    try {
        let { status, detail } = await getWeekVisitDataAPI({
            start: currentWeek.value.start.replace(/\./g, '-'),
            end: currentWeek.value.end.replace(/\./g, '-')
        })
        if (status !== 0) {
            uni.$u.toast(detail)
            return;
        }
        if(detail.product_title) {
            productTitle.value = detail.product_title;
        }
        //statr和end为key缓存到catchWeekData
        const key = currentWeek.value.start.replace(/\./g, '-') + currentWeek.value.end.replace(/\./g, '-');
        catchWeekData.value[key] = detail;
        form.value = {...detail};
    } catch (e) {
        console.log(e)
    }
}

//修改
function clickModify() {
    formDisabled.value = !formDisabled.value;
    formFocus.value = true;
}

//提交
function clickSubmit() {
    statisticsFormRef.value.validate().then(async valid => {
        if (valid) {
            try {
                let resData = {}
                let requestParams = {
                    ...form.value,
                    start: currentWeek.value.start.replace(/\./g, '-'),
                    end: currentWeek.value.end.replace(/\./g, '-'),
                }
                if(form.value.id) {
                    resData = await submitModifyStatisticsAPI(requestParams)
                } else {
                    resData = await submitCreateStatisticsAPI(requestParams)
                }
                if (resData.status !== 0) {
                    uni.$u.toast(resData.detail)
                    return;
                }
                uni.$u.toast('提交成功');
                // userInfoStore.setShowStatisticsForm(false);
            } catch (e) {
                console.log(e)
            }
        } else {
            uni.$u.toast('校验失败')
        }
    }).catch(() => {
        // 处理验证错误  
        uni.$u.toast('校验失败')
    });
}

</script>

<style scoped lang="scss">
.page {
    min-height: 100vh;
    overflow: hidden;

    .header {
        justify-content: space-between;
        padding: 10rpx 20rpx;

        .weekBtn {
            margin: 0;
        }
    }

    .districts {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 20rpx;
        padding: 20rpx;

        .district {
            padding: 10rpx 20rpx;
            border-radius: 10rpx;
        }

        .district.active {
            background-color: $theme-color;
            color: white;
        }
    }

    .formWrap {
        margin: 50rpx 28rpx 40rpx 28rpx;
    }

    .btn {
        width: 70%;
        margin: 40rpx auto;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 40rpx;
    }
}
</style>
